/*******************************************************************
 *
 * Copyright (C), 2021-2022, Letstrong, All rights reserved.
 *
 * Author      : 
 * Create Time : 2020-12-17
 * Version     : v0.1
 * Description : 
 *******************************************************************/
 
/*----------------------------Head file----------------------------*/
#include "hal_gpio.h"
#include "hal_battery.h"
#include "user_config.h"


#define HAL_BAT_LOG_EN		0

#if HAL_BAT_LOG_EN
#include "log.h"
#define HAL_BAT_LOG			LOG_DEBUG
#else
#define HAL_BAT_LOG(...)
#endif

/*----------------------------macro file---------------------------*/
#define FULL_CHARGE_DET_ENABLE()		hal_gpio_input_cfg(FULL_CHARGE_PIN_NUM, PULL_NONE)
#define FULL_CHARGE_DET_DISABLE()		hal_gpio_hires_cfg(FULL_CHARGE_PIN_NUM, PULL_NONE)		//CE3168A need to set CHG pin in hires to save consumption.

/*----------------------------type define--------------------------*/

/*----------------------------var define---------------------------*/
#if(BATT_CHARGE_ENABLE)
static hal_charge_evt_cb_t hal_charge_evt_cb = NULL;
#endif

/*-------------------------func declaration------------------------*/

/*-----------------------------------------------------------------*/

bool hal_batt_full_charge_state_get(void)
{
#if(BATT_CHARGE_ENABLE)
	FULL_CHARGE_DET_ENABLE();
	if(true == hal_gpio_read(DET_CHARGE_PIN_NUM) && true == hal_gpio_read(FULL_CHARGE_PIN_NUM)) {
		FULL_CHARGE_DET_DISABLE();
		return true;
	}
	else {
		FULL_CHARGE_DET_DISABLE();
		return false;
	}
#else
	return false;
#endif
}


bool hal_batt_charging_state_get(void)
{
#if(BATT_CHARGE_ENABLE)
	if(true == hal_gpio_read(DET_CHARGE_PIN_NUM))
		return true;
	else
		return false;
#else
	return false;
#endif
}


#if(BATT_CHARGE_ENABLE)
static void batt_charge_evt_hdl(uint8_t pin_num)
{
	if(hal_charge_evt_cb) {
		hal_charge_evt_cb(true);
	}
}
#endif


void hal_batt_charge_hw_init(hal_charge_evt_cb_t cb)
{
#if(BATT_CHARGE_ENABLE)
	hal_gpio_input_cfg(DET_CHARGE_PIN_NUM, PULL_NONE);
	hal_gpio_int_enable(DET_CHARGE_PIN_NUM, RAISING_EDGE, batt_charge_evt_hdl);

	FULL_CHARGE_DET_DISABLE();
	hal_charge_evt_cb = cb;
#endif
}


void hal_batt_charge_hw_deinit(void)
{
	//Set it to hires, or MCU can not enter deep sleep mode.
#if(BATT_CHARGE_ENABLE)
	hal_gpio_hires_cfg(DET_CHARGE_PIN_NUM, PULL_NONE);
	hal_gpio_hires_cfg(FULL_CHARGE_PIN_NUM, PULL_NONE);
#endif
}


void hal_batt_adc_measure(void)
{
	adc_trigger();
}


void hal_batt_adc_init(hal_adc_cb_t cb)
{
	adc_calibration();
	adc_cb_register(cb);
}

void hal_batt_adc_deinit(void)
{
	adc_deinit();
	hal_gpio_hires_cfg(BATT_ADC_PIN_NUM, PULL_NONE);
}
